#include "stdafx.h"
#include "SimpleChildProcess.h"
#include "WindowsUtility.h"

namespace RoomFW {

SimpleChildProcess::SimpleChildProcess()
{
    ::ZeroMemory(&si_, sizeof(si_));
    si_.cb = sizeof(si_);
    ::ZeroMemory(&pi_, sizeof(pi_));
}

SimpleChildProcess::~SimpleChildProcess()
{
	::CloseHandle(pi_.hProcess);
	::CloseHandle(pi_.hThread);
}


bool SimpleChildProcess::create(const char* applicationName, char* commandLine)
{
	si_.cb = sizeof(si_);
	si_.dwFlags = STARTF_USESHOWWINDOW;
	si_.wShowWindow = SW_SHOWMINIMIZED;//SW_MINIMIZE;

	bool retVal = ::CreateProcess(
		applicationName,  // Module name. 
        commandLine,      // Command line. 
        NULL,             // Process handle not inheritable. 
        NULL,             // Thread handle not inheritable. 
        FALSE,            // Set handle inheritance to FALSE. 
        CREATE_NEW_CONSOLE,                // creation flags. 
        NULL,             // Use parent's environment block. 
        NULL,             // Use parent's starting directory. 
        &si_,              // Pointer to STARTUPINFO structure.
        &pi_);             // Pointer to PROCESS_INFORMATION structure.
	SHOW_LAST_ERROR(retVal, "SimpleChildProcess::create", "::CreateProcess");
	return retVal;
}

bool SimpleChildProcess::wait(DWORD timeout) const
{
	return ::WaitForSingleObject(pi_.hProcess, timeout) ? true : false;
}

void SimpleChildProcess::kill()
{
	DWORD dwExitCode;
	int k=0;
	GetExitCodeProcess(pi_.hProcess, &dwExitCode);
	
	::TerminateProcess(pi_.hProcess,dwExitCode);
}

}
